package org.tigris.atlas.quizme.client.action;

import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.tigris.atlas.messages.Message;
import org.tigris.atlas.messages.MessageFactory;
import org.tigris.atlas.messages.MessageUtils;
import org.tigris.atlas.messages.Messages;
import org.tigris.atlas.quizme.client.form.QuizForm;
import org.tigris.atlas.quizme.client.utils.ClientUtils;
import org.tigris.atlas.quizme.client.utils.Constants;
import org.tigris.atlas.quizme.service.QuestionCollectionServiceResponse;
import org.tigris.atlas.quizme.service.QuizServiceResponse;
import org.tigris.atlas.quizme.service.delegate.QuizServiceDelegate;
import org.tigris.atlas.quizme.service.delegate.ServiceDelegateFactory;
import org.tigris.atlas.quizme.transfer.Quiz;
import org.tigris.atlas.quizme.transfer.UserProfile;

/**
 * Prepares a Quiz.  User is allows to enter any number of questions and the 
 * atlas-quizme-service project creates a quiz with that many questions randomly
 * selected from the datbase.
 * 
 * @author Robert Simmering
 */
public class CompileQuizAction  extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
		      HttpServletRequest request, HttpServletResponse response) {	
		QuizForm quizForm = (QuizForm)form;
		
		// Clear out the session so we can start a new quiz
		request.getSession().removeAttribute(Constants.QUESTIONS_KEY);
		request.getSession().removeAttribute(Constants.CURRENT_QUESTION_KEY);
		request.getSession().removeAttribute(Constants.QUESTION_INDEX_KEY);
		request.getSession().removeAttribute(Constants.ANSWERS_KEY);
			
		// determine the user enter number of questions to be on the quiz. Default to 10
		String sNumQuestions = quizForm.getQuizNumQuestions();
		Integer numQuestions;
		if(sNumQuestions == null || sNumQuestions.length()==0){
			numQuestions = new Integer(10);
		}
		else{
			try{
				int iNumQuestions = Integer.parseInt(sNumQuestions);
				if(iNumQuestions == 0){
					throw new NumberFormatException();
				}
				numQuestions = new Integer(iNumQuestions);
			}
			catch(NumberFormatException e){
				Message msg = MessageUtils.createErrorMessage("error.num.questions.invalid", null, null);
				Messages messages = MessageFactory.createMessages();
				messages.addMessage(msg);
				ClientUtils.getMessagesHandler().handleMessages(messages, quizForm.getClass(), request);
				return mapping.findForward("fail");
			}
		}
		
		UserProfile currentUser = (UserProfile)request.getSession().getAttribute(Constants.USER_KEY);
		
		// Call the Atlas Serivce to prepare the quiz
		QuizServiceDelegate sd = ServiceDelegateFactory.createQuizServiceDelegate();
		QuizServiceResponse quizResponse = sd.prepareQuiz(numQuestions,currentUser);
		if(quizResponse.getMessages().hasErrorMessages()){
			ClientUtils.getMessagesHandler().handleMessages( quizResponse.getMessages(), quizForm.getClass(), request);
			return mapping.findForward("fail");
		}
		
		// Retrieve the quiz from the service response
		Quiz quiz = quizResponse.getQuiz();
	    request.getSession().setAttribute(Constants.QUIZ_KEY, quiz);
	    QuestionCollectionServiceResponse questionsResponse = sd.getRandomQuestions(quizForm.getQuizTopicId(), numQuestions);
	    if(questionsResponse.getMessages().hasErrorMessages()){
	    	ClientUtils.getMessagesHandler().handleMessages( questionsResponse.getMessages(), quizForm.getClass(), request);
			return mapping.findForward("fail");
		}
		
		Collection questions = questionsResponse.getItems();
	    request.getSession().setAttribute(Constants.QUESTIONS_KEY, new ArrayList(questions));
	    
	    Integer questionIndex = new Integer(-1);
	    request.getSession().setAttribute(Constants.QUESTION_INDEX_KEY, questionIndex);
	    
		return mapping.findForward("success");
	}
	
	
}
